/**
 * Copyright (c) 2020, Mr.Wang (recallcode@aliyun.com) All rights reserved.
 */

package com.cpipec.demo.todo.impl;

import cn.hutool.db.Entity;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.cpipec.demo.spi.BPMServerRestClient;
import com.cpipec.demo.todo.TodoFinshService;
import com.cpipec.demo.vo.PageResultVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class TodoFinshServiceImpl implements TodoFinshService {

	@Autowired
	private BPMServerRestClient bpmServerRestClient;

	@Override
	public PageResultVO<Entity> getTodoFinshList(String username, int page, int pageSzie) {
		String bpmResult = bpmServerRestClient.getCompleteTaskList(username, page, pageSzie);
		JSONArray dataItems = JSONObject.parseObject(bpmResult).getJSONObject("ObjRetVal").getJSONArray("dataItems");
		List<Entity> entityList = new ArrayList<Entity>();
		dataItems.forEach(dataItem -> {
			Entity entity = new Entity();
			String stepName = JSONObject.parseObject(dataItem.toString()).getString("PENDINGSTEPNAME");
			if (!"发起者".equals(stepName)) {
				entity.set("taskId", JSONObject.parseObject(dataItem.toString()).getString("PENDINGCODE"));
				entity.set("bpmName", JSONObject.parseObject(dataItem.toString()).getString("PENDINGPROCESSNAME"));
				entity.set("instanceId", JSONObject.parseObject(dataItem.toString()).getString("PENDINGINCIDENT"));
				entity.set("stepName", JSONObject.parseObject(dataItem.toString()).getString("PENDINGSTEPNAME"));
				entity.set("todofinshName", JSONObject.parseObject(dataItem.toString()).getString("PENDINGOWNERNAME"));
				entity.set("todofinshNameCode", JSONObject.parseObject(dataItem.toString()).getString("PENDINGOWNER"));
				entity.set("startTime", JSONObject.parseObject(dataItem.toString()).getString("PENDINGDATE"));
				entity.set("endTime", JSONObject.parseObject(dataItem.toString()).getString("LASTUPDATEDATE"));
				entity.set("sourceName", JSONObject.parseObject(dataItem.toString()).getString("PENDINGSOURCEUSERNAME"));
				entity.set("sourceNameCode", JSONObject.parseObject(dataItem.toString()).getString("PENDINGSOURCEUSERID"));
				entity.set("tableName", JSONObject.parseObject(dataItem.toString()).getString("RESERVED_1"));
				entity.set("sourceId", JSONObject.parseObject(dataItem.toString()).getString("RESERVED_2"));
				entity.set("taskName", JSONObject.parseObject(dataItem.toString()).getString("RESERVED_3"));
				entity.set("startName", JSONObject.parseObject(dataItem.toString()).getString("RESERVED_4"));
				entity.set("startNameCode", JSONObject.parseObject(dataItem.toString()).getString("PENDINGFORMID"));
				entityList.add(entity);
			}
		});
		return new PageResultVO<Entity>(entityList, entityList.size());
	}
}
